<template>
  <div class="voice-to-text">
    <el-card class="box-card">
      <div slot="header" class="clearfix">
        <span>语音转文字</span>
      </div>
      <div class="content">
        <el-button 
          type="primary" 
          :icon="isRecording ? 'el-icon-microphone' : 'el-icon-microphone'"
          @click="toggleRecording"
          :loading="isProcessing"
        >
          {{ isRecording ? '停止录音' : '开始录音' }}
        </el-button>
        <div v-if="recognizedText" class="result-text">
          <h3>识别结果：</h3>
          <p>{{ recognizedText }}</p>
        </div>
      </div>
    </el-card>
  </div>
</template>

<script>
import axios from 'axios'

export default {
  name: 'VoiceToText',
  data() {
    return {
      isRecording: false,
      isProcessing: false,
      mediaRecorder: null,
      audioChunks: [],
      recognizedText: '',
      apiUrl: 'http://localhost:9999/api/voice/recognize'
    }
  },
  methods: {
    async toggleRecording() {
      if (!this.isRecording) {
        await this.startRecording()
      } else {
        await this.stopRecording()
      }
    },
    async startRecording() {
      try {
        const stream = await navigator.mediaDevices.getUserMedia({ audio: true })
        this.mediaRecorder = new MediaRecorder(stream)
        this.audioChunks = []

        this.mediaRecorder.ondataavailable = (event) => {
          this.audioChunks.push(event.data)
        }

        this.mediaRecorder.start()
        this.isRecording = true
        this.$message.success('开始录音')
      } catch (error) {
        console.error('Error accessing microphone:', error)
        this.$message.error('无法访问麦克风')
      }
    },
    async stopRecording() {
      return new Promise((resolve) => {
        this.mediaRecorder.onstop = async () => {
          const audioBlob = new Blob(this.audioChunks, { type: 'audio/wav' })
          await this.sendAudioToServer(audioBlob)
          this.isRecording = false
          resolve()
        }
        this.mediaRecorder.stop()
      })
    },
    async sendAudioToServer(audioBlob) {
      this.isProcessing = true
      try {
        const formData = new FormData()
        formData.append('audio', audioBlob)
        
        const response = await axios.post(this.apiUrl, formData, {
          headers: {
            'Content-Type': 'multipart/form-data'
          }
        })
        
        if (response.data.success) {
          this.recognizedText = response.data.text
          this.$message.success('语音识别成功')
        } else {
          this.$message.error('语音识别失败')
        }
      } catch (error) {
        console.error('Error sending audio:', error)
        this.$message.error('发送音频失败')
      } finally {
        this.isProcessing = false
      }
    }
  }
}
</script>

<style scoped>
.voice-to-text {
  padding: 20px;
}

.content {
  display: flex;
  flex-direction: column;
  align-items: center;
}

.result-text {
  margin-top: 20px;
  padding: 15px;
  border: 1px solid #dcdfe6;
  border-radius: 4px;
  width: 100%;
  max-width: 600px;
}

.result-text h3 {
  margin: 0 0 10px 0;
  color: #606266;
}

.result-text p {
  margin: 0;
  color: #303133;
  white-space: pre-wrap;
  word-break: break-all;
}
</style> 